package com.chen;

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfRect;
import org.opencv.core.Point;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.highgui.HighGui;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import org.opencv.objdetect.CascadeClassifier;

/**
 * 静态图检测人脸
 *
 * @author scorpius
 */
public class ImageRecognition {

    /**
     * 脸部检测并标注
     *
     * @param rgb RGB图像
     * @param gray 灰度图像
     */
    public static void faceAnalysis(Mat rgb, Mat gray) {
        CascadeClassifier cascade = new CascadeClassifier("/usr/local/share/opencv4/lbpcascades/lbpcascade_frontalcatface.xml");
        if (cascade.empty()) {
            System.err.println("文件路径有误...");
            return;
        }
        if (cascade.empty()) {
            System.out.println("文件读取失败");
            return;
        }
        MatOfRect rect = new MatOfRect();
        cascade.detectMultiScale(gray, rect);
        for (Rect re : rect.toArray()) {
            Imgproc.rectangle(rgb, new Point(re.x, re.y), new Point(re.x
                    + re.width, re.y + re.height), new Scalar(0, 255, 0));
        }
    }

    public static void main(String[] args) {
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
        Mat img = Imgcodecs.imread("/home/scorpius/Pictures/timg.jpeg");
        if (img.empty()) {
            System.err.println("图片路径有误...");
            return;
        }
        Imgproc.cvtColor(img, img, Imgproc.COLOR_BGR2RGB);
        Mat grayMat = new Mat();
        Imgproc.cvtColor(img, grayMat, Imgproc.COLOR_RGB2GRAY);
        faceAnalysis(img, grayMat);
        HighGui.imshow("show", img);
        HighGui.waitKey();
    }
}
